<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-form :inline="true">
          <el-form-item label="分类">
            <category-cascader :categoryPath.sync="categoryPath"></category-cascader>
          </el-form-item>
          <el-form-item label="选择课程">
            <course-select style="width:160px"></course-select>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div v-if="inputMenuParent && inputMenuParent2" style="width:30%;">
          <el-form :inline="true" :model="formOneStep" class="demo-form-inline">
            <el-form-item label="步骤标题">
              <el-input v-model="formOneStep.stepName" placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-form-item label="阅读人数">
              <el-input-number v-model="formOneStep.readNum" :min="0" :max="10000"></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="OneStudyStepButton">提交数据</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div v-if="!inputMenuParent">
          <el-switch v-model="draggableStep" active-text="开启拖拽" inactive-text="关闭"></el-switch>
          <el-button @click="batchSaveStep">批量保存</el-button>
          <el-button type="danger" round @click="batchDeleteStep">批量删除</el-button>
        </div>
        <el-tree
          :data="menus"
          node-key="stepId"
          :props="defaultPropsStep"
          :expand-on-click-node="false"
          show-checkbox
          :default-expanded-keys="expandedKeyStep"
          :draggable="draggableStep"
          :allow-drop="allowDropStep"
          @node-drop="handleDropStep"
          ref="menuTreeStep"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button
                v-if="node.level <= 3"
                type="text"
                size="mini"
                @click="() => appendStep(data)"
              >添加</el-button>
              <el-button
                v-if="node.childNodes.length == 0"
                type="text"
                size="mini"
                @click="() => removeStep(node, data)"
              >删除</el-button>
              <el-button type="text" size="mini" @click="() => editStep(data)">修改</el-button>
              <el-tag type="danger">热度：{{node.data.readNum}}</el-tag>
            </span>
          </span>
        </el-tree>
      </el-col>
    </el-row>

    <el-dialog
      :title="titleStep"
      :visible.sync="dialogVisibleStep"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="studyStep">
        <el-form-item label="步骤名称">
          <el-input v-model="studyStep.stepName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="阅读人数">
          <el-input v-model="studyStep.readNum" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleStep = false">取 消</el-button>
        <el-button type="primary" @click="submitDataStep">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CategoryCascader from "../common/category-cascader";
import CourseSelect from "../common/course-select";
// import attrsupdate from "./attrsupdate";, attrsupdate
export default {
  //import引入的组件需要注入到对象中才能使用
  components: { CategoryCascader, CourseSelect },
  watch: {
    courseId(val) {
      this.formOneStep.stepName = "";
      this.formOneStep.readNum = 0;
      if (val && val != 0) {
        console.log("课程->", val);
        this.$http({
          url: this.$http.adornUrl(`/ly/studystep/list/tree/${val}`),
          method: "get",
          params: this.$http.adornParams({})
        }).then(({ data }) => {
          console.log("检测到courseId的改变", data);
          this.menus = data.data;
          if (data.data == null || data.data.length < 1) {
            this.inputMenuParent = true;
          } else {
            this.inputMenuParent = false;
          }
          this.pSid = [];
          this.updateStudyStep = [];
          this.maxLevelStep = 0;
          this.inputMenuParent2 = true;
        });
      } else {
        this.inputMenuParent2 = false;
      }
    }
  },
  data() {
    return {
      formOneStep: {
        parentSid: 0,
        stepLevel: 1,
        courseId: 0,
        readNum: 0,
        stepName: "",
        sort: 0,
        status: 1
      },
      inputMenuParent: true,
      inputMenuParent2: false,
      pSid: [],
      draggableStep: false,
      updateStudyStep: [],
      maxLevelStep: 0,
      studyStep: {
        stepId: null,
        parentSid: 0,
        stepLevel: 1,
        courseId: 0,
        sort: 0,
        readNum: 0,
        status: 1,
        stepName: ""
      },
      titleStep: "",
      dialogTypeStep: "", //edit,add
      dialogVisibleStep: false,
      expandedKeyStep: [],
      categoryPath: [],
      courseId: 0,
      categoryId: 0,
      catPathSub: null,
      courseIdSub: null,
      menus: [],
      defaultPropsStep: {
        children: "children",
        label: "stepName"
      }
    };
  },
  methods: {
    OneStudyStepButton() {
      this.formOneStep.courseId = this.courseId;
      console.log("首次提交的数据喂", this.formOneStep);
      this.$http({
        url: this.$http.adornUrl("/ly/studystep/save"),
        method: "post",
        data: this.$http.adornData(this.formOneStep, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "标题添加成功!"
        });
        //刷新出新的菜单
        this.getMenusStep();
        this.inputMenuParent=false;
      });
    },
    batchDeleteStep() {
      let stepIds = [];
      let checkedNodes = this.$refs.menuTreeStep.getCheckedNodes();
      for (let i = 0; i < checkedNodes.length; i++) {
        stepIds.push(checkedNodes[i].stepId);
      }
      if (stepIds == null || stepIds.length < 1) {
        return;
      }
      this.$confirm(`此操作将批量删除该课程[${stepIds}], 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/ly/studystep/delete"),
            method: "post",
            data: this.$http.adornData(stepIds, false)
          }).then(({ data }) => {
            this.$message({
              type: "success",
              message: "菜单批量删除成功!"
            });
            //刷新出新的菜单
            this.getMenusStep();
          });
        })
        .catch(() => {});
    },
    batchSaveStep() {
      if (this.updateStudyStep.length < 1 || this.updateStudyStep == null) {
        return;
      }
      this.$http({
        url: this.$http.adornUrl("/ly/studystep/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateStudyStep, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "顺序修改成功!"
        });
        //刷新出新的菜单
        this.getMenusStep();
        //设置需要展开的菜单
        this.expandedKeyStep = this.pSid;
        this.updateStudyStep = [];
        this.maxLevelStep = 0;
      });
    },
    handleDropStep(draggingNode, dropNode, dropType, ev) {
      let pSid = 0;
      let sibLings = null;
      if (dropType == "before" || dropType == "after") {
        pSid =
          dropNode.parent.data.stepId == undefined
            ? 0
            : dropNode.parent.data.stepId;
        sibLings = dropNode.parent.childNodes;
      } else {
        pSid = dropNode.data.stepId;
        sibLings = dropNode.childNodes;
      }
      this.pSid.push(pSid);
      for (let i = 0; i < sibLings.length; i++) {
        if (sibLings[i].data.stepId == draggingNode.data.stepId) {
          let stepLevel = draggingNode.level;
          if (sibLings[i].level != draggingNode.level) {
            stepLevel = sibLings[i].level;
            this.updateChildrenLevelStep(sibLings[i]);
          }
          this.updateStudyStep.push({
            stepId: sibLings[i].data.stepId,
            parentSid: pSid,
            sort: i,
            stepLevel: stepLevel
          });
        } else {
          this.updateStudyStep.push({
            stepId: sibLings[i].data.stepId,
            sort: i
          });
        }
      }
      console.log("最新层级", this.updateStudyStep);
    },
    updateChildrenLevelStep(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data;
          this.updateStudyStep.push({
            stepId: cNode.stepId,
            stepLevel: node.childNodes[i].level
          });
          this.updateChildrenLevelStep(node.childNodes[i]);
        }
      }
    },
    allowDropStep(draggingNode, dropNode, type) {
      //统计当前节点的最大深度
      this.countNodeLevelStep(draggingNode);
      //当前节点+父节点所在的深度不大于3
      let deep = Math.abs(this.maxLevelStep - draggingNode.level) + 1;
      console.log("深度", deep);
      if (type == "inner") {
        return deep + dropNode.level <= 4;
      } else {
        return deep + dropNode.parent.level <= 4;
      }
    },
    countNodeLevelStep(node) {
      //找到所有子节点，求出最大深度
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevelStep) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevelStep(node.childNodes[i]);
        }
      }
    },
    submitDataStep() {
      if (this.dialogTypeStep == "add") {
        this.addStudyStep();
      }
      if (this.dialogTypeStep == "edit") {
        this.editStudyStep();
      }
    },
    editStep(data) {
      this.dialogTypeStep = "edit";
      this.titleStep = "修改步骤";
      this.dialogVisibleStep = true;
      //发送请求获得最新的数据
      this.$http({
        url: this.$http.adornUrl(`/ly/studystep/info/${data.stepId}`),
        method: "get",
        params: this.$http.adornParams({})
      }).then(({ data }) => {
        this.studyStep.stepName = data.data.stepName;
        this.studyStep.stepId = data.data.stepId;
        this.studyStep.readNum = data.data.readNum;
        this.studyStep.parentSid = data.data.parentSid;
      });
    },
    editStudyStep() {
      let { stepId, stepName, readNum } = this.studyStep;
      this.$http({
        url: this.$http.adornUrl("/ly/studystep/update"),
        method: "post",
        data: this.$http.adornData({ stepId, stepName, readNum }, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "修改成功!"
        });
        this.dialogVisibleStep = false;
        //刷新出新的菜单
        this.getMenusStep();
        //设置需要展开的菜单
        this.expandedKeyStep = [this.studyStep.parentSid];
      });
    },
    removeStep(node, data) {
      var ids = [data.stepId];
      var parentIds = [data.parentSid];
      this.$confirm(`此操作将删除该步骤[${data.stepName}], 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/ly/studystep/delete"),
            method: "post",
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            //刷新出新的菜单
            this.getMenusStep();
            //设置需要展开的菜单
            this.expandedKeyStep = [node.parent.data.stepId];
          });
        })
        .catch(() => {});
      console.log(node, data);
    },
    addStudyStep() {
      console.log("提交的数据", this.studyStep);
      this.$http({
        url: this.$http.adornUrl("/ly/studystep/save"),
        method: "post",
        data: this.$http.adornData(this.studyStep, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "添加成功!"
        });
        this.dialogVisibleStep = false;
        //刷新出新的菜单
        this.getMenusStep();
        //设置需要展开的菜单
        this.expandedKeyStep = [this.studyStep.parentSid];
      });
    },
    appendStep(data) {
      this.dialogTypeStep = "add";
      this.titleStep = "添加步骤";
      this.dialogVisibleStep = true;
      //准备数据
      this.studyStep.courseId = data.courseId;
      this.studyStep.parentSid = data.stepId;
      this.studyStep.stepLevel = data.stepLevel * 1 + 1;

      this.studyStep.stepName = "";
      this.studyStep.stepId = null;
      this.studyStep.readNum = 0;
      this.studyStep.sort = 0;
      this.studyStep.status = 1;
    },
    getMenusStep() {
      this.$http({
        url: this.$http.adornUrl(`/ly/studystep/list/tree/${this.courseId}`),
        method: "get",
        params: this.$http.adornParams({})
      }).then(({ data }) => {
        console.log("成功获得数据", data);
        this.menus = data.data;
      });
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.catPathSub = PubSub.subscribe("catPath", (msg, val) => {
      this.categoryId = val[val.length - 1];
    });
    this.courseIdSub = PubSub.subscribe("courseId", (msg, val) => {
      this.courseId = val;
    });
  },
  beforeDestroy() {
    PubSub.unsubscribe(this.catPathSub);
    PubSub.unsubscribe(this.courseIdSub);
  }
};
</script>

<style>
</style>